<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">部门管理</text>
     
    </view>
    
    <!-- 搜索过滤区 -->
    <view class="search-filter">
      <view class="search-bar">
        <uni-icons type="search" size="18" color="#909399" class="search-icon"></uni-icons>
        <input 
          type="text" 
          placeholder="搜索部门名称" 
          v-model="searchKey"
          @input="filterDepartments"
          class="search-input"
        >
		<button class="action-btn add-btn" @click="openModal('add')">
		  <uni-icons type="plus" size="18" color="#fff"></uni-icons>
		  <text>添加部门</text>
		</button>
      </view>
      
     
    </view>
    
    <!-- 部门列表 -->
    <view class="department-list">
		  <deptNode v-for="dept in departments"
		  :key="dept.dept_id"
		  :dept="dept" 
		  :level="0"
		  @edit="edit()"
		  @delete="showDeleteConfirm()"></deptNode>
    
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredDepartments.length === 0">
        <uni-icons type="empty" size="80" color="#C0C4CC"></uni-icons>
        <text class="empty-text">暂无部门数据</text>
        <button class="action-btn add-btn" @click="openModal('add')">
          <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          <text>添加部门</text>
        </button>
      </view>
    </view>
    
    <!-- 分页控件 -->
    <view class="pagination" v-if="totalPages > 1">
      <button class="page-btn" :class="{ disabled: currentPage === 1 }" @click="goToPage(1)">
        <uni-icons type="arrowleft" size="16"></uni-icons>
      </button>
      
      <button 
        class="page-btn" 
        v-for="page in pageNumbers" 
        :key="page" 
        :class="{ active: page === currentPage }"
        @click="goToPage(page)"
      >
        {{ page }}
      </button>
      
      <button class="page-btn" :class="{ disabled: currentPage === totalPages }" @click="goToPage(totalPages)">
        <uni-icons type="arrowright" size="16"></uni-icons>
      </button>
    </view>
    
    <!-- 部门操作弹窗 -->
    <view v-if="modalVisible" class="modal-overlay">
      <view class="modal-container" :class="modalType === 'add' ? 'add-modal' : 'edit-modal'">
        <view class="modal-header">
          <text class="modal-title">{{ modalType === 'add' ? '添加部门' : '编辑部门' }}</text>
          <view class="close-btn" @click="closeModal">
            <uni-icons type="close" size="20" color="#909399"></uni-icons>
          </view>
        </view>
        
        <view class="modal-form">
          <view class="form-group">
            <label class="form-label">部门名称 <text class="required">*</text></label>
            <input 
              type="text" 
              v-model="form.dept_name" 
              placeholder="请输入部门名称"
              class="form-input"
              :class="{ 'input-error': errors.name }"
              @focus="clearError('name')"
            >
            <text class="error-message" v-if="errors.name">{{ errors.name }}</text>
          </view>
          
          <view class="form-group">
            <label class="form-label">上级部门</label>
            <picker 
              mode="selector" 
              :range="parentOptionsList" 
              :range-key="parentKey"
              @change="parentO"
              class="picker"
            >
              <view class="picker-content">
                {{ getSelectedParentName(form.parent_id) }}
              </view>
            </picker>
          </view>
          
          <view class="form-group">
            <label class="form-label">负责人</label>
            <input 
              type="text" 
              v-model="form.leader" 
              placeholder="请输入负责人姓名"
              class="form-input"
              @focus="clearError('leader')"
            >
            <text class="error-message" v-if="errors.leader">{{ errors.leader }}</text>
          </view>
          
          <view class="form-group">
            <label class="form-label">联系电话</label>
            <input 
              type="tel" 
              v-model="form.phone" 
              placeholder="请输入联系电话"
              class="form-input"
              @input="validatePhone"
              @focus="clearError('phone')"
            >
            <text class="error-message" v-if="errors.phone">{{ errors.phone }}</text>
          </view>
          <view class="form-group">
            <label class="form-label">排序</label>
            <input 
              type="number" 
              v-model="form.order_num" 
              placeholder="请输入..."
              class="form-input"
              
            >
          </view>
          <view class="form-group">
            <label class="form-label">部门状态 <text class="required">*</text></label>
            <view class="status-radio-group">
              <view 
                class="status-radio-item" 
                v-for="(item, index) in statusOptions" 
                :key="index"
                :class="form.status==item.value?'active':'' "
                @click="form.status = item.value"
              >
                {{ item.label }}
              </view>
            </view>
            <text class="error-message" v-if="errors.status">{{ errors.status }}</text>
          </view>
          
          <view class="form-group">
            <label class="form-label">邮箱</label>
			<input
			  type="tel" 
			  v-model="form.email" 
			  placeholder="请输入邮箱"
			  class="form-input"
			  
			>
          <!--  <textarea 
              v-model="form.description" 
              placeholder="请输入部门描述（选填）" 
              class="form-textarea"
              maxlength="500"
              @focus="clearError('description')"
            ></textarea> -->
          </view>
        </view>
        
        <view class="confirm-actions">
          <button style="justify-content: center;" class="action-btn cancel-btn" @click="closeModal">取消</button>
          <button  style="justify-content: center;" class="action-btn confirm-btn" @click="submitForm">
            {{ modalType === 'add' ? '添加' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view v-if="showDeleteModal" class="delete-confirm-overlay">
      <view class="delete-confirm-container">
        
        <view style="text-align: center; padding-bottom: 35rpx;" class="confirm-title">确认删除</view>
        <text class="confirm-message">你确定要删除<span class="delete-dept-title">{{ deptToDelete.name }}</span>吗？此操作不可恢复。</text>
        <view class="confirm-actions" style="margin-top: 35rpx;">
          <button  style="justify-content: center;" class="action-btn cancel-btn" @click="showDeleteModal = false">取消</button>
          <button   style="justify-content: center;"class="action-btn confirm-btn" @click="deleteDepartment">确认删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import deptNode from '@/components/deptNode.vue'
export default {
  components:{deptNode},
  data() {
    return {
      departments: [], // 部门数据
      searchKey: '', // 搜索关键词
      filter: {
        status: '',
        parent: ''
      }, // 过滤条件
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      totalPages: 1, // 总页数
      totalDepts: 0, // 总部门数
      statusOptions: [ // 状态选项
        { value: 0, label: '启用' },
        { value: 1, label: '停用' }
      ],
      modalVisible: false, // 弹窗显示状态
      modalType: 'add', // 弹窗类型 add/edit
      form: { // 部门表单数据
        parent_id: 0,
        leader: '',
        phone: '',
        dept_name: '',
        status: 0,
        order_num: 0,
		email:''
      },
      errors: {}, // 表单错误信息
      showDeleteModal: false, // 删除确认弹窗显示状态
      deptToDelete: null, // 待删除的部门
      originalDept: null, // 原始部门数据（编辑时使用）
	  parentOptionsList:[],
	  list:[]
    }
  },
  onLoad() {
    this.getDept();
	this.getDeptSelectOptions()
  },
  computed: {
    // 过滤后的部门列表
    filteredDepartments() {
      let result = this.departments;
      
      // 搜索过滤
      if (this.searchKey) {
        const key = this.searchKey.toLowerCase();
        result = result.filter(dept => 
          dept.dept_name.toLowerCase().includes(key)  
        );
      }
      
      // 状态过滤
      if (this.filter.status) {
        result = result.filter(dept => dept.status === this.filter.status);
      }
      
      // 上级部门过滤
      if (this.filter.parent) {
        result = result.filter(dept => dept.parent_id == this.filter.parent);
      }
      
      // 分页处理
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.totalDepts = result.length;
      this.totalPages = Math.ceil(this.totalDepts / this.pageSize);
      
      return result.slice(start, end);
    },
    // 页码列表
    pageNumbers() {
      const numbers = [];
      const start = Math.max(1, this.currentPage - 2);
      const end = Math.min(this.totalPages, start + 4);
      
      for (let i = start; i <= end; i++) {
        numbers.push(i);
      }
      
      return numbers;
    },
    // 上级部门选项（排除当前编辑的部门）
    parentOptions() {
	
      if (this.originalDept && this.modalType === 'edit') {
        // 编辑时排除当前部门及其子部门
        return this.departments.filter(dept => {
          if (dept.parent_id === this.originalDept.parent_id) return false;
          return !this.hasChild(dept.parent_id, this.originalDept.parent_id);
        });
      }
      // 添加时排除根部门自身（根部门parentId为0）
      return this.departments.filter(dept => dept.parent_id !== this.form.parent_id);
    },
    // 根部门列表（用于过滤条件）
    rootDepartments() {
      return this.departments.filter(dept => dept.parent_id === 0);
    }
  },
  methods: {
	parentO(e){
		console.log(e)
		let index = e.detail.value
		this.form.parent_id = this.list[index].value
	},
	async getDeptSelectOptions(){
		const res = await this.$api.get('/Dept/getDeptSelectOptions','',true)
		if(res.data.code == 200) {
			res.data.data.forEach(item => {
				this.parentOptionsList.push(item.label)
			})
			this.list = res.data.data
		}
	},
	async getDept(){
		const res = await this.$api.get('/Dept/getDeptTree',{keyword:this.searchKey},true)
		if(res.data.code === 200) {
			this.departments = res.data.data
		}
	},

    // 过滤部门
    filterDepartments() {
      this.page = 1;
	  this.getDept()
    },
    // 切换过滤条件
    toggleFilter(type, value) {
      this.filter[type] = value;
      this[currentPage === 1 ? 'filterDepartments' : 'goToPage'](1);
      this.filter[type] = value ? value : false;
    },
    // 前往指定页面
    goToPage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
    },
    // 获取上级部门名称
    getParentName(parentId) {
      if (parentId === 0) return '无上级部门';
      const parent = this.departments.find(dept => dept.id === parentId);
      return parent ? parent.name : '未知部门';
    },
    // 获取选中的上级部门名称
    getSelectedParentName(parentId) {
      if (parentId === 0) return '无上级部门';
      const parent = this.parentOptions.find(dept => dept.dept_id === parentId);
      return parent ? parent.dept_name : '请选择上级部门';
    },
    // 检查是否有子部门（用于编辑时排除子部门）
    hasChild(parentId, excludeId) {
      return this.departments.some(dept => dept.dept_id === parentId && dept.dept_id !== excludeId);
    },
	//编辑
	edit(data,dept) {
		this.modalType = 'edit'
		this.resetForm();
		this.modalVisible = true;
		this.form = data
		this.originalDept = data
		console.log('编辑',data,this.originalDept)
	},
    // 打开弹窗
    openModal(type, dept = null) {
      this.modalType = type;
      this.resetForm();
      
      if (type === 'edit' && dept) {
        this.originalDept = { ...dept };
        this.form.name = dept.name;
        this.form.code = dept.code;
        this.form.parentId = dept.parentId;
        this.form.leader = dept.leader;
        this.form.phone = dept.phone;
        this.form.staffCount = dept.staffCount;
        this.form.status = dept.status;
        this.form.description = dept.description;
      }
      
      this.modalVisible = true;
    },
    // 关闭弹窗
    closeModal() {
      this.modalVisible = false;
      this.resetForm();
      this.originalDept = null;
    },
    // 重置表单
    resetForm() {
      this.form = {
        parent_id: 0,
        leader: '',
        phone: '',
        dept_name: '',
        status: 0,
        order_num: 0,
		email:''
      };
      this.errors = {};
	  this.getDept()
    },
    // 清除单个错误
    clearError(field) {
      this.errors[field] = '';
    },
    // 验证电话格式
    validatePhone(e) {
      const phone = e.detail.value;
      if (phone) {
        this.form.phone = phone.replace(/[^\d]/g, '').substr(0, 11);
      }
    },
    // 验证表单
    validateForm() {
      const errors = {};
      
      if (!this.form.dept_name) errors.dept_name = '请输入部门名称';
      if (this.form.status === '') errors.status = '请选择部门状态';
      
      if (this.form.phone && !/^1[3-9]\d{9}$/.test(this.form.phone)) {
        errors.phone = '请输入正确的电话号码';
      }
      return errors;
    },
    // 提交表单
    async  submitForm() {
      this.errors = this.validateForm();
      if (Object.keys(this.errors).length > 0) return;
	  console.log('this.modalType',this.modalType)
	
	  if(this.modalType == 'edit'){
		  const res = await this.$api.post('/Dept/editDept',this.form,true)
		  if(res.data.code === 200) {
		  		   uni.showToast({ title:  '保存成功',icon: 'none'  });
		  		  this.departments = []
		  		  this.getDept()
		  		  this.closeModal();
		  		  this.page = 1
		  }
	  } else {
		 const res = await this.$api.post('/Dept/addDept',this.form,true)
		 if(res.data.code === 200) {
		 		   uni.showToast({ title: '添加成功',icon: 'none'  });
		 		  this.departments = []
		 		  this.getDept()
		 		  this.closeModal();
		 		  this.page = 1
		 } 
	  }
      
     
      
    },
    // 显示删除确认
    showDeleteConfirm(dept) {
	  console.log('大大大',dept)
      this.deptToDelete = dept;
      this.showDeleteModal = true;
    },
    // 删除部门
    async deleteDepartment() {
      if (!this.deptToDelete) return;
      
	  const res = await this.$api.post('/Dept/deleteDept',{dept_id:this.deptToDelete.dept_id},true)
	  if(res.data.code === 200) {
		  this.page = 1
		  this.getDept()
		  this.showDeleteModal = false;
		  this.deptToDelete = null;
		  uni.showToast({ title: '删除成功', icon: 'none' });
	  }
      // 检查是否有子部门
      if (this.departments.some(dept => dept.parentId === this.deptToDelete.id)) {
        uni.showToast({
          title: '该部门有子部门，无法删除',
          icon: 'none'
        });
        this.showDeleteModal = false;
        return;
      }
      
      uni.showLoading({ title: '删除中...' });
      setTimeout(() => {
        uni.hideLoading();
        const index = this.departments.findIndex(dept => dept.id === this.deptToDelete.id);
        if (index !== -1) {
          this.departments.splice(index, 1);
          uni.showToast({ title: '删除成功', icon: 'success' });
        }
        this.showDeleteModal = false;
        this.deptToDelete = null;
      }, 800);
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<style lang="scss" scoped>
/* 基础布局 (与岗位管理页面一致，以下仅列出差异部分) */
.container { /* 同岗位管理页面样式 */ }

/* 部门列表 */
.department-list { /* 同岗位管理页面 .job-list 样式 */ }

.department-card {
  /* 同岗位管理页面 .job-card 样式，仅修改类名 */
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  padding: 30rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
  animation: fadeInUp 0.5s ease forwards;
  opacity: 0;
  transform: translateY(20rpx);
  
  &:hover { box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1); transform: translateY(-2rpx); }
}

.department-header {
  /* 同岗位管理页面 .job-header 样式，仅修改类名 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .department-name { font-size: 32rpx; font-weight: 600; color: #303133; }
  .department-code { font-size: 24rpx; color: #909399; background-color: #F0F2F5; padding: 4rpx 12rpx; border-radius: 4rpx; }
}

.department-info {
  /* 同岗位管理页面 .job-info 样式，仅修改类名 */
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
  
  .info-item {
    flex: 1;
    min-width: 50%;
    margin-bottom: 16rpx;
    
    .info-label { font-size: 24rpx; color: #909399; margin-right: 10rpx; }
    .info-value { font-size: 28rpx; color: #303133; }
  }
}

.department-footer {
  /* 同岗位管理页面 .job-footer 样式，仅修改类名 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .department-status {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    font-weight: 500;
    
    &.status-active { color: #67c23a; background-color: rgba(103, 194, 58, 0.1); }
    &.status-inactive { color: #e6a23c; background-color: rgba(230, 162, 60, 0.1); }
  }
  
  .department-create-time { font-size: 24rpx; color: #909399; }
  .department-actions { display: flex; }
}


</style>